/**
 * 版权所有 Copyright@yyk1504@163.com
 */
package com.fairy.sso.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fairy.core.encrypt.DESCoder;
import com.fairy.core.encrypt.SHACoder;
import com.fairy.core.util.MD5Util;
import com.fairy.core.util.NetUtil;
import com.fairy.sso.SSOConstants;
import com.fairy.sso.Ticket;
import com.fairy.sso.annotation.FairyControllerExceptionLog;
import com.fairy.sso.cache.SSOCache;
import com.fairy.sso.config.DomainCollection;
import com.fairy.sso.config.FairyConfig;
import com.fairy.sso.core.CookieHelper;
import com.fairy.sso.core.NetHelp;
import com.fairy.sso.core.SSOHelp;
import com.fairy.sso.entity.SSOUserEntity;
import com.fairy.sso.server.Factory;
import com.fairy.sso.server.SSOCacheFactory;
import com.fairy.sso.service.SSOService;
import com.fairy.web.common.FairyConstants;

/**
 * [LoginController.java.java]
 *
 * @Author: [yyk1504@163.com]
 * @CreateDate: [2016-03-18 1:38:35]
 * @Update: [说明本次修改内容] by [yyk1504@163.com] [2016-03-18 1:38:35]
 * @Version: [v1.0]
 */

@Controller
public class LoginController {
	private static Logger log = Logger.getLogger(LoginController.class);
	@Autowired(required=true)
	private FairyConfig fairyConfig;
	
	@Autowired(required=true)
	private SSOService<SSOUserEntity> ssoService;
	
	
	@Autowired
	private DomainCollection domainCollection;
	
	@RequestMapping ("/login.do")
	@FairyControllerExceptionLog(description="用户登录")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr)
	{
		log.info("=========================="+SSOConstants.temp);
		SSOConstants.temp++;
	    ModelAndView mav = new ModelAndView("index"); 
	    String accountNo = request.getParameter("accountNo");
        String passWord = request.getParameter("passWord");
        String codeImg=request.getParameter("codeImg");
        log.info("用户输入的验证码:"+codeImg);
        String service = request.getParameter(SSOConstants.CLIENT_URL);
        HttpSession session = request.getSession();  
        String code=(String)session.getAttribute("sso-code");  
        log.info("session中已经保存的验证码:"+code);
        
        log.info("session中 code:"+code+",页面传过来的code:"+codeImg);
        if(null!=code&&!"".equals(code))
        {
        	if(codeImg.equalsIgnoreCase(code))
        	{
        		
        		log.info("session中 code:"+code+",页面传过来的code:"+codeImg+",验证通过");
        		session.removeAttribute("sso-code");
        		String domain=NetHelp.getDomain(service);
                List<String>list=domainCollection.getDomainList();
                if(null!=domain&&!"".equals(domain)&&!list.contains(domain))
                {
                	//非法域名，防钓鱼
                	attr.addFlashAttribute("tips", "非法的来源域名"); 
                	attr.addFlashAttribute("service", service);  	
                	mav=new ModelAndView("redirect:/index.do?service=" + service);
                }
                else
                {
                    SSOUserEntity ssoUserEntity=ssoService.login(accountNo, passWord);
                    if(null!=ssoUserEntity&&null!=ssoUserEntity.getUserId()&&!"".equals(ssoUserEntity.getUserId()))
                    {
                    	//HttpSession session=request.getSession();
                    	String ticketSecretkey=fairyConfig.getSsoTicketSecretkey();
                    	String ip=NetUtil.getIpAddr(request);
                        Ticket ticket=new Ticket();
                        long time = System.currentTimeMillis();
                        String clusterIp=fairyConfig.getSsoClientUrl();
                        //String md5Ticket=getMD5Ticket(ticket);
                        String md5Ticket=SSOHelp.getMD5Ticket(clusterIp, ticketSecretkey);
                        ticket.setIp(ip);
                        ticket.setTime(time);
                        ticket.setUserId(ssoUserEntity.getUserId());
                        ticket.setAccountNo(accountNo);
                        ticket.setClusterIp(clusterIp);                        
                        ticket.setTicketKey(md5Ticket);
                        
                        //String md5Ticket=MD5Util.GetMD5Code( ticketStr);
                        log.info("ticket md5:"+md5Ticket);
       
                        //String key = userName + time;
                        //String key = t.toString();
                        //JVMCache.TICKET_AND_NAME.put(timeString, username);
                        
                        //Map<String,String>map=SSOHelp.getTicketIpMap(md5Ticket, cilentUrl);
                        
                        Factory factory = new SSOCacheFactory(); 
                        String cacheType=fairyConfig.getCacheType();
                        SSOCache cache = factory.createSSOCache(cacheType); 
                        
                        cache.set(md5Ticket, ticket);

                        
                        
                        //ssoService.saveTicket(ticket, md5Ticket);
                        log.info("从缓存取ticket:"+cache.get(md5Ticket).toString());
                        
    
 
                        
                        CookieHelper.addCookie(response, fairyConfig.getDomain(), fairyConfig.getPath(), SSOConstants.SSO_COOKIE_KEY,md5Ticket, fairyConfig.getMaxAge());
                        
                        if (null != service) {
                            StringBuilder url = getURL(service, md5Ticket);
                            log.info("登录成功::"+url.toString());
            				try {
            					response.sendRedirect(url.toString());
            				} catch (IOException e) {
            					e.printStackTrace();
            				}
                        } 
                        else 
                        {
                        	//没有跳转上文链接
                        	attr.addFlashAttribute("tips", "没有跳转上文链接"); 
                        	mav=new ModelAndView("redirect:/index.do");
                        }
                    } 
                    else 
                    {
                    	//用户不存在
                    	attr.addFlashAttribute("service", service); 
                    	attr.addFlashAttribute("tips", "用户不存在"); 
                        //attr.addFlashAttribute("success", "添加成功!");
                    	mav=new ModelAndView("redirect:/index.do?service=" + service);
            			//response.sendRedirect("/sso-server/index.jsp?service=" + service)
                    }        	
                }
                
        	}
        	else
        	{
        		//验证码输入错误
        		attr.addFlashAttribute("tips", "验证码输入错误"); 
        		mav=new ModelAndView("redirect:/index.do");
        	}
        }
        
	    return mav; 
	}

	@RequestMapping ("/logout.do")
	@FairyControllerExceptionLog(description="用户注销")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String ticket)
	{
		ModelAndView mav=new ModelAndView("redirect:/");
		
        String service = request.getParameter(SSOConstants.CLIENT_URL);
        mav=new ModelAndView("redirect:"+service);
        CookieHelper.removeCookie(request, response, SSOConstants.SSO_COOKIE_KEY);
        Factory factory = new SSOCacheFactory(); 
        String cacheType=fairyConfig.getCacheType();
        SSOCache cache = factory.createSSOCache(cacheType); 
        cache.delete(ticket);
	    //mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,username);

        return mav;
	}
	
	@RequestMapping ("/logout2.do")
	@FairyControllerExceptionLog(description="用户注销")
	public ModelAndView logout2(HttpServletRequest request, HttpServletResponse response,Model model,RedirectAttributes attr,String ticket)
	{
		//ModelAndView mav=new ModelAndView("redirect:/");
		ModelAndView mav = new ModelAndView(FairyConstants.JSON_VIEW_RETAIN_DEFINED_VIEW); 
        //String service = request.getParameter(SSOConstants.CLIENT_URL);
        //mav=new ModelAndView("redirect:"+service);
		String str="";
        CookieHelper.removeCookie(request, response, SSOConstants.SSO_COOKIE_KEY);
        try
        {
	        Factory factory = new SSOCacheFactory(); 
	        String cacheType=fairyConfig.getCacheType();
	        SSOCache cache = factory.createSSOCache(cacheType); 
	        cache.delete(ticket);
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
	    mav.addObject(FairyConstants.JSON_VIEW_RETAIN_DATA,str);
        return mav;
	}
	/**
	private String getMD5Ticket(String ticket) {
		String str_rev="";
		//String ticketStr=ticket.toString();
		log.info("生成 ticket:"+ticket);
		
		byte[] inputData = ticket.getBytes(); 
		String key=fairyConfig.getSsoTicketSecretkey();
		try {
			inputData = DESCoder.encrypt(inputData, key);
			String mi=DESCoder.encryptBASE64(inputData);
			 log.info("加密后::"+mi);
			 byte[] outputData = DESCoder.decrypt(inputData, key);  
		     String outputStr = new String(outputData);  
		     log.info("解密后::"+outputStr);
		     String str=SHACoder.sha512Encode(mi);
		     log.info("SHA512::"+str);
		     str_rev=MD5Util.GetMD5Code(str);
		     log.info("MD5::"+str_rev);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return str_rev;
	}*/
	private StringBuilder getURL(String service, String md5Ticket) {
		StringBuilder url = new StringBuilder();
		url.append(service);
		if (0 <= service.indexOf("?")) {
		    url.append("&");
		} else {
		    url.append("?");
		}
		url.append("ticket=").append(md5Ticket);
		return url;
	}
}
